package web

import (
	"context"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"

	"gitee.com/crack007/goose/gsconfig"
	"gitee.com/crack007/goose/gscore"
	"gitee.com/crack007/goose/gslog"
	"github.com/gin-gonic/gin"
)

type HttpServer struct {
	handle  IHttpServerHandle
	port    uint16
	Builder *HttpServerBuilder
	Engine  *gin.Engine
	gscore.BaseServer
	server *http.Server
}

func (x *HttpServer) SetPort(port uint16) {
	x.port = port
}

func (x *HttpServer) GetPort() uint16 {
	return x.port
}

func (x *HttpServer) InjectHandle(iHandle gscore.IHandle) {
	if v, ok := iHandle.(IHttpServerHandle); ok {
		x.handle = v
		return
	}

	panic("httpServerHandle type error")
}

func (x *HttpServer) GetBuilder() gscore.IBuilder {
	return x.Builder
}

func (x *HttpServer) OnBeforeRun() {
	x.handle.OnBeforeRun()
}

func (x *HttpServer) OnBeforeInit() {
	x.handle.OnInjectServer(x)
	x.handle.OnBeforeInit()
}

// 解析config配置
func (x *HttpServer) OnInitConfig() {
	var err error
	defer func() {
		if err != nil {
			panic("OnInitConfig err: " + err.Error())
		}
	}()

	if x.Builder.GetConfigPath() != "" {
		gsconfig.ParseConfig(x.Builder.GetConfigPath(), x.Builder.ConfigObject)
		if v, ok := x.Builder.ConfigObject.(gscore.AppConfig); ok {
			if v.Log != nil {
				gslog.DefaultLog = gslog.NewConsoleLogger(v.Log)
			}
		}
	}

	if x.Builder.GetLogDebug() {
		gslog.DefaultLog.SetLogLevel(gslog.LEVEL_DEBUG)
	}

	if x.Builder.GetLogTrace() {
		gslog.DefaultLog.SetLogLevel(gslog.LEVEL_TRACE)
	}

	x.handle.OnInitConfig()
}

func (x *HttpServer) OnInitInject() {

}

func (x *HttpServer) OnBuild() {
	if !x.Builder.GetLogDebug() && !x.Builder.GetLogTrace() {
		gin.SetMode(gin.ReleaseMode)
		gin.DefaultWriter = ioutil.Discard
	}

	x.Engine = gin.Default()
}

func (x *HttpServer) OnInitService() {
	x.handle.OnInitService()
}

func (x *HttpServer) OnInitRouter() {
	x.handle.OnInitResource()
	x.handle.OnInitRouter()
}

func (x *HttpServer) OnRun() {
	x.AddGracefulTask(gscore.NewGracefulTask(func(ctx context.Context) {
		address := fmt.Sprintf(":%d", x.port)
		gslog.Warn("http server [%s] listen: %s", x.GetServerName(), address)
		x.server = &http.Server{
			Addr:    address,
			Handler: x.Engine,
		}
		err := x.server.ListenAndServe()
		if err != nil {
			if !errors.Is(err, http.ErrServerClosed) {
				panic(err)
			}
		}
	}))

	go func() {
		<-x.Done()
		gslog.Warn("http server [%s] exit", x.GetServerName())
		x.handle.OnShutdown()
		x.server.Shutdown(x.Ctx)
	}()

	x.GracefulExit()
}
